import { loadEnv, defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import path from 'path';
// 配置svg-icon
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
// 配置按需加载element-plus
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';

// https://vitejs.dev/config/
export default defineConfig(async ({ command, mode }) => {
  return {
    //定义全局变量
    define: {
      'process.env': loadEnv(mode, process.cwd()),
    },
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver({ importStyle: 'sass' })],
      }),
      Components({
        resolvers: [ElementPlusResolver({ importStyle: 'sass' })],
      }),
      createSvgIconsPlugin({
        // 配置你存放 svg 图标的目录
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // 定义 symbolId 格式
        symbolId: 'icon-[dir]-[name]',
      }),
    ],
    //配置本地服务器
    server: {
      hmr: true,
      port: 8001,
      open: true,
      proxy: {
        '/api': {
          target: 'https://thunders.com.hk/website/',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, ''),
          secure: false,
        },
      },
    },
    base: '/manage/',
    resolve: {
      extensions: ['.vue', '.jsx', '.js'],
      alias: {
        '@': path.resolve(__dirname, 'src'),
        '@cmpts': path.resolve(__dirname, 'src/components'),
        '@utils': path.resolve(__dirname, 'src/utils'),
      },
    },
    css: {
      // css预处理器
      preprocessorOptions: {
        scss: {
          /*
            引入var.scss全局预定义变量，
            如果引入多个文件，
            可以使用
            '@import "@/assets/css/sc1.scss";@import "@/assets/css/sc2.scss";'
            这种格式
          */
          additionalData: '@use "@/assets/css/var.scss" as *;',
        },
      },
    },
    build: {
      outDir: 'thunderAdmin',
      rollupOptions: {
        output: {
          //入口文件输出配置
          entryFileNames: `js/[name]-[hash].js`,
          //代码分割后的文件输出配置
          chunkFileNames: `js/[name]-[hash].js`,
          //静态资源输出配置
          assetFileNames(assetInfo) {
            //css文件单独输出到css文件夹
            if (assetInfo.name.endsWith('.css')) {
              return `css/[name]-[hash].css`;
            }
            //图片文件单独输出到img文件夹
            else if (
              ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp'].some(ext =>
                assetInfo.name.endsWith(ext),
              )
            ) {
              return `img/[name]-[hash].[ext]`;
            }
            //其他资源输出到assets文件夹
            else {
              return `[name]-[hash].[ext]`;
            }
          },
        },
      },
    },
    esbuild: {
      jsx: 'preserve',
      drop: mode === 'prod' ? ['console', 'debugger'] : ['debugger'],
    },
  };
});
